// CP(生产消费) 模型
//基于阻塞队列,实现生产消费模型
//1.解耦(生产与消费互不依赖)
//2.并发(生产与消费并发)
//3.闲忙不均(基于解耦和并发带来的效率提升)
#include "block_queue.hpp"
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <unistd.h>
using namespace std;

void *consumer_routine(void *queue_addr)
{
    block_queue<int> *block_queue_pointer = reinterpret_cast<block_queue<int> *>(queue_addr);
    while (1)
    {
        //生产
        int product = rand() % 10;
        block_queue_pointer->push(product);
        cout << "成功产出 num: " << product << endl;
    }
}
void *producer_routine(void *queue_addr)
{
    block_queue<int> *block_queue_pointer = reinterpret_cast<block_queue<int> *>(queue_addr);
    while (1)
    {
        //消费
        int good=block_queue_pointer->pop();
        cout << "成功获取 num: " << good << endl;
    }
}
int main()
{
    //用于模拟生产的随机数种子
    block_queue<int> _block_queue;
    srand(static_cast<unsigned int>(time(static_cast<time_t *>(nullptr))) + getpid());
    pthread_t _consumer_tid, _producer_tid;
    pthread_create(&_consumer_tid,nullptr,consumer_routine,static_cast<void*>(&_block_queue));
    pthread_create(&_producer_tid,nullptr,producer_routine,static_cast<void*>(&_block_queue));
    pthread_join(_consumer_tid,nullptr);
    pthread_join(_producer_tid,nullptr);

    return 0;
}